/**
 * 
 */
package com.core.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 将汉字转换成拼音
 *  调用方法 : 
        new PinYin().toPinYin("中华人民共和国");
		new PinYin().toPinYin("中华人民共和国" , true , false);
		new PinYin().toPinYin("中华人民共和国" , true , true);
 * @author laker
 * @version 1.0 2010-12-01
 */
public class PinYin {
	/**
	 * 转入汉字,转换成拼音
	 * 
	 * @param str
	 * @return
	 */
	public String toPinYin(String str) {
		return this.toPinYin(str, false, false);
	}

	/**
	 * 转入汉字,转换成拼音
	 * 
	 * @param str
	 *            汉字
	 * @param isFirstCharToUpper
	 *            是否首字母大写 默认为false ,即全部小写(hupan)
	 * @param hasSpace
	 *            是否每个拼音之间包含空格 默认false , 即没有空格(hupan)
	 * @return
	 */
	public String toPinYin(String str, boolean isFirstCharToUpper,
			boolean hasSpace) {
		if (str == null || "".equals(str)) {
			return str;
		}
		String newString = "";
		HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
		t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		t3.setVCharType(HanyuPinyinVCharType.WITH_V);
		String[] temp = null;
		char[] strChar = str.toCharArray();
		boolean isZhiMu = false;
		try {
			for (int i = 0; i < strChar.length; i++) {
				char c = strChar[i];
				isZhiMu = false;
				if (String.valueOf(c).matches("[\\u4E00-\\u9FA5]+")) {
					temp = PinyinHelper.toHanyuPinyinStringArray(c, t3);
				} else if (((int) c >= 65 && (int) c <= 90)
						|| ((int) c >= 97 && (int) c <= 122)) {
					temp = new String[] { String.valueOf(strChar[i]) };
					isZhiMu = true;
				}  
				if (temp != null && temp.length > 0) {
					if (isZhiMu == false) {
						newString += (isFirstCharToUpper ? toUppString(temp[0]) : temp[0]) + (hasSpace ? " " : "");
					} else {
						newString += temp[0];
					}
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		System.out.println(str + " => "+ newString);
		return newString;
	}

	/**
	 * 将传过来的字符首字母大写
	 * 
	 * @param newS
	 * @return
	 */
	private String toUppString(String newS) {
		String s = "";
		char[] first = newS.toCharArray();
		for (int i = 0; i < first.length; i++) {
			s += String.valueOf((i == 0 ? (char) (first[i] + 'Z' - 'z')
					: (char) first[i]));
		}
		return s;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//new PinYin().toPinYin("中华人民共和国MD");
		new PinYin().toPinYin("中华人民共和国MM" , true , false);
		//new PinYin().toPinYin("中华人民共和国MN" , true , true);
	}

}
